package org.lsp.opencvauto;

import com.sun.jna.platform.DesktopWindow;
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import org.lsp.opencvauto.doman.MessageCoordinatesAndContent;
import org.lsp.opencvauto.image.ImageDispose;
import org.lsp.opencvauto.ocr.OCRInstanst;
import org.lsp.opencvauto.weixin.WeiXin;
import org.lsp.opencvauto.weixin.WeixinUI;
import org.lsp.opencvauto.windowApi.WindowDispose;
import org.opencv.core.*;
import org.opencv.core.Point;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Component
public class Start {


    private static final Logger log = LoggerFactory.getLogger(Start.class);

    private  final Robot robot =new Robot();

    @Autowired
    private WeixinUI weixinUI;
    @Autowired
    private WindowDispose window;

    @Autowired
    private ImageDispose image;

    @Autowired
    private WeiXin weiXin;
    private  final  static  String TARGETIMAGEURL="./weixin.png";
    private  final static  String TEMPLATEURL="matchTemplate/messagerecognition/1.png";
    private  final  static  String WEIXINYUANDIAN="matchTemplate/messagerecognition/4.jpg";//微信消息匹配模板

    public Start() throws AWTException {
    }

    public void startRun(){
        messageListen();
    }

    /**
     * 监听微信消息，并且自动回复
     *
     * */
    private  void messageListen(){
        Map<String, Object> map = window.windowTop();
        WinDef.RECT rect = new WinDef.RECT();
        DesktopWindow desktopWindow=(DesktopWindow)map.get("DesktopWindow");
        User32.INSTANCE.GetWindowRect(desktopWindow.getHWND(), rect);

        Rectangle rectangle = new Rectangle((Integer) map.get("x"), (Integer) map.get("y"), (Integer) map.get("width"), (Integer) map.get("height"));
        //指定截取的位置
//        Rectangle rectangle = new Rectangle(rect.left, `rect.`top, (Integer) map.get("width"), (Integer) map.get("height"));
        //截取窗口图片
        BufferedImage bufferedImage = window.captureRegion(rectangle);
        //保存截取的图片
        try {
//            boolean b = window.detectNewMessage(bufferedImage);
//            System.out.printf("detectNewMessage: %b\n", b);
            ImageIO.write(bufferedImage,"png",new FileOutputStream(TARGETIMAGEURL));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //识别窗口消息位置
        Map<String, Object> identification = image.identification(TEMPLATEURL,TARGETIMAGEURL);
        Core.MinMaxLocResult local =(Core.MinMaxLocResult)identification.get("minMaxLoc");
        log.info("模板匹配到的微信消息位置等信息 x: {} y: {}",local.maxLoc.x ,local.maxLoc.y );
        Mat mat = image.imageScreenshot((( Core.MinMaxLocResult) identification.get("minMaxLoc")).maxLoc,
                (Mat) identification.get("src"), (Mat) identification.get("templateGray"));
        Imgcodecs.imwrite("weixinxaioxiquyv.png",mat);
        Map<String, Object> weixinxiaoxi =image.identification(WEIXINYUANDIAN, "./weixinxaioxiquyv.png");
        Core.MinMaxLocResult weixinxiaoxiLocal =(Core.MinMaxLocResult)weixinxiaoxi.get("minMaxLoc");
        log.info(" weixinxiaoxiLocal模板匹配到的微信消息位置等信息 x: {} y: {}",weixinxiaoxiLocal.maxLoc.x ,weixinxiaoxiLocal.maxLoc.y );
        String messages = weiXin.identifyMessages("./weixinxaioxiquyv.png").trim().replace(" ","");
        log.info("识别的微信消息：{} 字符串长度：{}",messages,messages.length());

        if (messages.equals(" ")|| messages == null) {
            log.info("当前微信未监听到新消息");
            return;
        }

        if (!messages.matches("\\d+")) {
            log.info("识别错误");
            return;
        }

        //分割图片获得微信的消息区域

        Core.MinMaxLocResult messagesXY =weixinUI.weiXinMessages();
        ClassPathResource classPathResource = new ClassPathResource("matchTemplate/messagerecognition/messages.png");
        Mat messageTemp =null;
        try {
            messageTemp = Imgcodecs.imread(classPathResource.getFile().getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (messageTemp == null) {
            log.info("微信消息模板读取错误");
            return;
        }


        log.info("截取的微信消息区域的坐标 x:{} y: {} 长：{} 宽：{}",messagesXY.maxLoc.x,(Integer) map.get("y"),
                (int) (((Integer) map.get("width"))- messagesXY.maxLoc.x), (int) ((Integer) map.get("height")-messagesXY.maxLoc.y));
        Mat matMessage = image.imageScreenshot((Mat) identification.get("src"),
                messagesXY,
                messageTemp.cols(),
                (int) ((Integer) map.get("height")-messagesXY.maxLoc.y));
//
        Imgcodecs.imwrite("messageqvyv.png",matMessage);

        List<MessageCoordinatesAndContent> messageCoordinatesAndContents = weiXin.messageBarNotifications();

        if (messageCoordinatesAndContents.isEmpty()) {
            log.info("目前没有找到区域中的消息");
            int x= (int) ((Integer) map.get("x")+messagesXY.maxLoc.x);
            int y= (int) ((Integer) map.get("y")+messagesXY.maxLoc.y);
            int cols = matMessage.cols();
            int rows = matMessage.rows();
            robot.mouseMove(x+cols/2,y+rows/2);
            robot.mouseWheel(10);
        }else if (messageCoordinatesAndContents.size()>0) {

            for (int i = 0; i < messageCoordinatesAndContents.size(); i++) {
                //将鼠标移动到消息附件的坐标
                Rect rect1 = messageCoordinatesAndContents.get(i).getRect();
                int x= (int) ((Integer) map.get("x")+messagesXY.maxLoc.x)+rect1.x;
                int y= (int) ((Integer) map.get("y")+messagesXY.maxLoc.y)+rect1.y;
                //根据消息的坐标移动鼠标
                robot.mouseMove(x,y);
                //鼠标左键点击消息
                robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // 按下左键
                robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); // 释放左键robot.
                weiXin.sendMessage("你好");


            }

        }



    }


}
